<template>
  <!-- 表格 -->
  <el-table
    ref="multipleTableRef"
    :data="filterTableData"
    :style="{ width: w + 'px' }"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column label="用户名" prop="username" />
    <el-table-column label="创建时间" prop="time" />
    <el-table-column label="角色" prop="role" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    v-model:current-page="currentPage4"
    v-model:page-size="pageSize4"
    :page-sizes="[3, 5, 8]"
    :small="small"
    :disabled="disabled"
    :background="background"
    layout="total, sizes, prev, pager, next, jumper"
    :total="allNumber"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  {{ formFlag }}
  <!-- 编辑用户信息表单 -->
  <!-- :style="{'display':formFlag2}" -->
  <div class="form-box" v-show="formFlag" >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <!-- 单选框 -->
      <el-radio-group v-model="ruleForm.role" class="ml-4">
        <el-radio label="admin" size="large">admin</el-radio>
        <el-radio label="normal" size="large">normal</el-radio>
      </el-radio-group>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="sureForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="quitForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import request from "@/network/request";
import { onBeforeMount, onMounted, onUnmounted, ref } from "vue";

import { useIsCollapseStore } from "@/stores/iscollapse";
let $useIsCollapseStore = useIsCollapseStore();

let formFlag = ref(false);
let formFlag2 = ref("none");

let w = computed(() => {
  return $useIsCollapseStore.width;
});
// 分页
const currentPage4 = ref(1);
const pageSize4 = ref(3);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const allNumber = ref<number>(0);
const tableData = ref<User[]>([]);

interface PageT {
  startIndex: number;
  pageSize: number;
  excelName: string;
}

function localPage(data: PageT) {
  request({
    url: "/page",
    method: "get",
    params: data,
  }).then((res) => {
    // console.log("res",res);
    // console.log("tableData",tableData);
    tableData.value = res.data;
  });
}

// 挂载前发送请求，得到用户总数量
onBeforeMount(() => {
  request({
    url: "/allNumber",
    method: "get",
    params: {
      excelName: "users",
    },
  }).then((res) => {
    // console.log("用户列表：", res);
    allNumber.value = res.data[0]["COUNT(*)"];
  });

  //获取第一页的数据
  localPage(
    {
      startIndex: 0,
      pageSize: pageSize4.value,
      excelName: "users",
    },
    tableData
  );
});
// 每一个数据条数改变事件处理函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  localPage(
    {
      startIndex: (currentPage4.value - 1) * val,
      pageSize: val,
      excelName: "users",
    }
  );
};
// 页码改变事件处理函数
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  localPage(
    {
      startIndex: (val - 1) * pageSize4.value,
      pageSize: pageSize4.value,
      excelName: "users",
    }
  );

  console.log("当前页面数据：", tableData);
};

// 表格
import { computed } from "vue";

interface User {
  username: string;
  time: string;
  role: string;
  [propNmae: string]: string;
}

const search = ref("");
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) => !search.value || data.username.includes(search.value)
  )
);

// 编辑按钮的事件处理函数
const handleEdit = (index: number, row: User) => {
  console.log(index, row);
  // 表单盒子出现
  formFlag.value = true;
  formFlag2.value = "block";

  ruleForm.id = row.id;
  ruleForm.username = row.username;
  ruleForm.role = row.role;
};

// 删除按钮的事件处理函数
const handleDelete = (index: number, row: User) => {
  console.log(index, row);
  // 调删除接口，传入参数
};

// 多选
import { ElTable } from "element-plus";
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<User[]>([]);
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;

  console.log("选中", val);
};

// 修改用户信息表单
import { reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";

interface RuleForm {
  username: string;
  role: string;
  id: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  username: "12345",
  role: "admin",
  id: "",
});

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 5, message: "长度3-5", trigger: "blur" },
  ],
});

const sureForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 获取表单的值
      console.log(ruleForm);

      // 调用修改用户数据接口
      request({
        url: "/user/update",
        method: "get",
        params: ruleForm,
      }).then((res) => {
        console.log("返回结果：", res);
      });

      // 再次获取当前页码的数据
      localPage(
        {
          startIndex: (currentPage4.value - 1) * pageSize4.value,
          pageSize: pageSize4.value,
          excelName: "users",
        }
      );

      // 表单盒子消失
      formFlag.value = false;
      formFlag2.value = "none";
    } else {
      alert("请输入符合格式要求的内容");
    }
  });
};

const quitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  // 表单盒子消失
  formFlag.value = false;
  console.log("取消", formFlag);
  formFlag2.value = "none";

};
</script>

<style scoped lang="scss">
.form-box {
  width: 100vw;
  height: 100vh;
  background-color: rgba($color: #000000, $alpha: 0.5);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  .el-form {
    width: 300px;
    height: 300px;
    background-color: white;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 30px;
  }
}
</style>
